package com.binaryTree;

import java.util.Stack;

public class SumofLeftLeaves0302_404 {
    //递归
    public int sumOfLeftLeaves0(TreeNode root) {
        if(root == null) return 0;
        int leftVal = sumOfLeftLeaves(root.left);
        int rightVal = sumOfLeftLeaves(root.right);

        int midVal = 0;
        if(root.left != null && root.left.left == null && root.left.right == null) midVal = root.left.val;
        int sum = midVal + leftVal + rightVal;
        return sum;
    }

    //迭代
    public int sumOfLeftLeaves(TreeNode root) {
        if(root == null) return 0;
        Stack<TreeNode> sta = new Stack<>();
        sta.push(root);
        int res = 0;
        while (!sta.isEmpty()){
            TreeNode node = sta.pop();
            if(node.left != null && node.left.left == null && node.left.right == null) res += node.left.val;

            if (node.right != null) sta.push(node.right);
            if (node.left != null) sta.push(node.left);
        }
        return res;
    }
}
